import React from "react";
import { Form, Modal,  Spin, Button, Input, Select, Radio,Table,Popconfirm } from "antd";
import { getUuid,openNotificationWithIcon } from "../../../../utils/comm";

const formItemLayout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 15},
  };
  const formItemLayout2 = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  };
const {TextArea} = Input;

const { Option } = Select;
  @Form.create()
class EventCompensate extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      eventConfigData: [],
      deleteFlag:0,
    }
    this.openNotificationWithIcon = openNotificationWithIcon.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    const {eventConfigData,deleteFlag}=this.state;   // eslint-disable-line no-unused-vars
    const newEventConfig=nextProps.eventCompensateData;
    if(newEventConfig!==eventConfigData){
      this.setState({eventConfigData:newEventConfig});
    }
  }

  handleOk = (e) => {
    if (e && e.preventDefault) e.preventDefault();
  };

  handleCancel = () => {
     const { handleEventCompensateVisible } = this.props;
     handleEventCompensateVisible();
  };


  handleSubmit = (e) => {
    if (e && e.preventDefault) e.preventDefault();
    const { form, testEvent } = this.props;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      testEvent(values);
    });
  }

  handleEdit = (record) => {
    const { form } = this.props;
    // const configContent = record.configContent;
    form.setFieldsValue(record);
    // form.setFieldsValue({ configContent })
  }

  handleFormOk = e => {
    if (e && e.preventDefault) e.preventDefault();
    const {
      form,
    } = this.props;
    // this.forceUpdate();
    const {eventConfigData} = this.state;
    form.validateFields((err, values) => {
      if (!err) {
            if (values.key) {
              // console.log(values);
              // 编辑
              // eslint-disable-next-line array-callback-return
              eventConfigData.map(item => {
                if (item.key === values.key) {
                  item.name = values.name;
                  item.config = {url: values.config};
                  item.eventType = values.eventType;
                  item.callMethod = values.callMethod;
                  item.requestBody = values.requestBody;
                  item.desc = values.desc;
                }
              });
              this.setState({eventConfigData});
            } else {
              // 新增
              values.key = getUuid();
              values.config = {url: values.config};
              eventConfigData.push(values);
              this.setState({eventConfigData},);
            }
        form.resetFields();
      }
    });
  };

  handleReset=()=>{
    const { form } = this.props;
    form.resetFields();
  }

  handleDelete = record => {
    const {eventConfigData,deleteFlag} = this.state;
    // this.forceUpdate();
    if(eventConfigData){
      const eventConfig = eventConfigData.filter(v => v.key !== record.key);
      const flag=deleteFlag+1;
      this.setState({eventConfigData:eventConfig,deleteFlag:flag});
    }
  };
  // componentDidMount() {
  //   const {eventCompensateData={}} = this.props;
  //   const {eventConfigData}=this.state;
  //   this.setState({eventConfigData:eventCompensateData});
  // }


  getModelDetail = () => {
    const {eventConfigData}=this.state;
    // console.log(eventConfigData);
    const { dispatch } = this.props;
    if(eventConfigData.length>0){
      dispatch({
        type: "flowEvent/getModelDetail",
        payload:{
          modelId:eventConfigData[0].modelId,
        },
      }).then((res) => {
        if (res.errCode === 0) {
          //  const nodes=res.datas.modelJson.nodes;
          //  console.log(nodes);
          //  var j=0,len=nodes.length,flag=1,k=0;
          //  for(j=0;j<len;j++){
          //   var eventconfigs=nodes[j].model.properties.eventConfig;
          //   if(eventconfigs){
          //     for(k=0;k<eventconfigs.length;k++){
          //       var temp={};
          //       temp.id=flag;
          //       temp.modelKey=res.datas.key;
          //       temp.modelId=res.datas.modelId;
          //       temp.modelName=res.datas.name;
          //       temp.nodeName=nodes[j].model.properties.name;
          //       temp.nodeCode=nodes[j].model.properties.overrideid;
          //       temp.callMethod=eventconfigs[k].callMethod;
          //       temp.eventType=eventconfigs[k].eventType;
          //       temp.eventName=eventconfigs[k].name;
          //       temp.url=eventconfigs[k].config.url;
          //       temp.requestBody=eventconfigs[k].requestBody;
          //       temp.desc=eventconfigs[k].desc;
          //       eventDataTemp.push(temp);
          //       flag=flag+1;
          //     }
          //   }
          // }
        }
    })
    }
  };

  render() {
    const{eventConfigData,deleteFlag}=this.state;  // eslint-disable-line no-unused-vars
    const {
      visible,
      eventCompensateLoaded=false,
      eventCompensateData,// eslint-disable-line no-unused-vars
      form,
      testEvent,// eslint-disable-line no-unused-vars
      eventList,
      dispatch,// eslint-disable-line no-unused-vars
    } = this.props;
     const { getFieldDecorator } = form; // getFieldValue
     const eventColumns = [
      {
        title: '节点编码',
        dataIndex: 'nodeCode',
        key: 'nodeCode',
        align: 'center',
      },
      {
        title: '事件名称',
        dataIndex: 'name',
        key: 'name',
        align: 'center',
      },
      {
        title: '事件url',
        dataIndex: 'configContent',
        key: 'configContent',
        align: 'center',
      },
      {
        title: "事件类型",
        dataIndex: "callMethod",
        // render: value => (value === "sync" ? "同步" : "异步"),
        render: (text)=> {
          if(text === "sync") return "同步";
          if(text === "async") return "异步";
          else return "";
        },
      },
      {
        title: '事件类型',
        dataIndex: 'eventType',
        key: 'eventType',
        align: 'center',
        // render: (text, record) => {
        //   return <span>{record.eventType === "" ? '-' : (record.eventType === "ACTIVITY_STARTED" ? '流程前置' : "流程后置")}</span>
        // },
        render: (text)=> {
          if(text === "ACTIVITY_STARTED" || text === "TASK_CREATED" ) return "流程前置";
          if(text === "ACTIVITY_COMPLETED" || text === "TASK_COMPLETED" ) return "流程后置";
          else return "";
        },
      },
      {
        title: "操作",
        align: 'center',
        render: (text, record) => {
          return (
            <div>
              <a
                onClick={(e) => {
                  e.preventDefault();
                  this.handleEdit(record);
                }}
                style={{ marginRight: '10px' }}
              >
                编辑
              </a>
              <Popconfirm
                placement="left"
                title={`确定删除事件：${record.name}?`}
                onConfirm={() => {
                  this.handleDelete(record);
                }}
                okText="确定"
                cancelText="取消"
              >
                <a
                  onClick={(e) => {
                    e.preventDefault();
                  }}
                >
                  删除
                </a>
              </Popconfirm>
            </div>
          );
        },
      }];
    return (
      <Modal
        title="事件在线查看"
        visible={visible}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
        width="1000px"
        centered
        destroyOnClose
        footer={null}
      >
        <Spin spinning={eventCompensateLoaded}>
          <div style={{height: '850px',width:'800px', paddingTop:'5px'}}>
            <Form>
              <Form.Item>
                {getFieldDecorator("key", {
                        initialValue: "",
                    })(<Input type='hidden' />)}
              </Form.Item>
              <Form.Item>
                {getFieldDecorator("modelId", {
                        initialValue: "",
                    })(<Input type='hidden' />)}
              </Form.Item>
              <Form.Item label="节点编码" {...formItemLayout}>
                {getFieldDecorator("nodeCode", {
                        initialValue: "",
                    })(<Input type='text' readOnly="readonly" />)}
              </Form.Item>
              <Form.Item label="事件名称" {...formItemLayout}>
                {getFieldDecorator("name", {
                        initialValue:"",
                        rules: [
                        { required: true, message: "请输入事件名称" },
                        ],
                    })(<Input placeholder="请输入事件名称" />)}
              </Form.Item>
              <Form.Item label="事件url" {...formItemLayout}>
                {getFieldDecorator("configContent", {
                        initialValue: "",
                        rules: [
                        { required: true, message: "请输入事件url" },
                        ],
                    })(<Input placeholder="请输入事件url" />)}
              </Form.Item>
              <Form.Item label="requestBody" {...formItemLayout}>
                {getFieldDecorator("requestBody", {
                        initialValue: "",
                    })(<TextArea
                      rows={4}
                        // eslint-disable-next-line no-template-curly-in-string
                      placeholder='{ &#13;&#10;
                        "流程实例Id":"${_processInstanceId}",&#13;&#10;
                        "发起人Id":"${_applyUserId}" &#13;&#10;
                    }'
                    />)}
              </Form.Item>
              <Form.Item label="事件触发时机" {...formItemLayout}>
                {getFieldDecorator('eventType', {
                        initialValue: "",
                    })(
                      <Select placeholder="请选择事件触发时机">
                        {/* <Option value="ACTIVITY_STARTED">流程前置</Option>
                        <Option value="ACTIVITY_COMPLETED">流程后置</Option> */}
                        {eventList.map(event=><Option key={event.value}>{event.name}</Option>)}
                      </Select>,
                    )}
              </Form.Item>
              <Form.Item label="        " {...formItemLayout2} colon={false}>
                {getFieldDecorator('callMethod', {
                        initialValue: "sync",
                    })(
                      <Radio.Group>
                        <Radio value="sync">同步</Radio>
                        <Radio value="async">异步</Radio>
                      </Radio.Group>,
                    )}
              </Form.Item>
              <Form.Item label="事件备注" {...formItemLayout}>
                {getFieldDecorator("desc", {
                        initialValue:"",
                    })(<TextArea maxLength={200} rows={2} placeholder="请输入事件备注" />)}
              </Form.Item>
              <Form.Item label="回调参数" {...formItemLayout}>
                {getFieldDecorator("callbackParam", {
                  initialValue: "",
                })(<Input placeholder="请输入回调参数" />)}
              </Form.Item>
              <Form.Item>
                <Button onClick={this.handleSubmit} type="primary">
                  测试
                </Button>
                {/* <React.Fragment>
                      <Link
                        to={{
                          pathname: "/flowmanage/flowchart",
                          search: queryString.stringify({
                            modelId: eventCompensateData.modelId,
                            //modelStatus: record.modelStatus,
                          }),
                        }}
                      >
                        <Button type="primary" style={{ float: 'right' }}>
                            编辑事件
                        </Button>
                      </Link>
                </React.Fragment> */}
                <Button onClick={this.handleReset}>
                  重置
                </Button>
                {/* <Button type="primary" onClick={this.handleFormOk}>
                  添加
                </Button> */}
                {/* <Button  onClick={this.getModelDetail} style={{cssFloat: "right"}}>
                            保存
                        </Button> */}
              </Form.Item>
            </Form>
            <Table
              style={{width: "900px"}}
              bordered
              columns={eventColumns}
              dataSource={eventConfigData}
              pagination={false}
            />
          </div>
        </Spin>
      </Modal>
    )
  }
}

export default EventCompensate;
